package com.applink.sell_proof;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ActivityManager;
import android.content.Intent;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.applink.sell_proof.builder.AbstractBuilder;
import com.applink.sell_proof.builder.PopupBuilder;
import com.applink.sell_proof.dialog.MyProgressDialog;
import com.applink.sell_proof.util.Utility;

/**
 * 
 * @author Van Vu
 * 
 */
public abstract class AbstractActivity extends SherlockFragmentActivity
		implements OnClickListener {

	private PopupWindow mPopUpSell;
	private PopupWindow mPopUpAnnoucement;
	private AbstractBuilder mBuilderSell;
	private AbstractBuilder mBuilder;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.deal_tab: {
			View mLayout = findViewById(R.id.pager);
			if (mLayout == null)
				mLayout = findViewById(R.id.main_container);
			if (mPopUpSell == null) {
				View popuplayout = View.inflate(this, R.layout.popupwindow,
						null);
				mBuilderSell = new PopupBuilder(this, (ViewGroup) popuplayout);
				List<HashMap<String, String>> mapdata = new ArrayList<HashMap<String, String>>() {
					private static final long serialVersionUID = -4260374979605439442L;
					{
						add(new HashMap<String, String>() {

							private static final long serialVersionUID = 8652504496866077589L;

							{
								put("title",
										getResources().getString(
												R.string.pricebook));
								put("className",
										"com.applink.sell_proof.PriceBookActivity");
								put("classShowing", getClassName());
							}
						});

						add(new HashMap<String, String>() {
							/**
							 * 
							 */
							private static final long serialVersionUID = 1395606277921789882L;

							{
								put("title",
										getResources().getString(
												R.string.product));
								put("className",
										"com.applink.sell_proof.ProductActivity");
								put("classShowing", getClassName());
							}
						});
					}
				};

				mBuilderSell.setData(mapdata);

				mPopUpSell = new PopupWindow(this);
				mPopUpSell.setContentView(popuplayout);
				mPopUpSell.dismiss();
			}

			if (mPopUpSell.isShowing()) {
				mPopUpSell.dismiss();
			} else {

				int listheight = 0;

				if (mBuilderSell != null) {
					listheight = Utility
							.getListViewHeight(((PopupBuilder) mBuilderSell)
									.getListView());
				}

				View bottombar = findViewById(R.id.main_bottom_bar);
				if (bottombar == null)
					bottombar = findViewById(R.id.tab_bar_group);

				// get maximum possible height
				int height = mPopUpSell.getMaxAvailableHeight(mLayout);
				int width = mLayout.getWidth() * 2 / 3;

				// location should be the bottom left
				mPopUpSell.showAtLocation(mLayout, Gravity.BOTTOM
						| Gravity.LEFT, 0, height);
				mPopUpSell.update(0, bottombar.getMeasuredHeight(), width,
						(listheight + 10));
			}

			break;
		}
		case R.id.learn_tab: {
			Intent intent = new Intent(this, LearnActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(intent);
			break;
		}
		case R.id.custservice_tab: {
			Intent intent = new Intent(this, CustomerServiceActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(intent);
			break;
		}
		case R.id.reward_tab: {
			Intent intent = new Intent(this, RewardActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(intent);
		}
			break;
		case R.id.announce_tab: {
			View mLayout = findViewById(R.id.pager);

			if (mLayout == null)
				mLayout = findViewById(R.id.main_container);

			if (mPopUpAnnoucement == null) {

				View popuplayout = View.inflate(this, R.layout.popupwindow,
						null);

				mBuilder = new PopupBuilder(this, (ViewGroup) popuplayout);

				List<HashMap<String, String>> mapdata = new ArrayList<HashMap<String, String>>() {

					private static final long serialVersionUID = -4071147297803061098L;

					{
						add(new HashMap<String, String>() {

							private static final long serialVersionUID = 5683197566296917650L;

							{
								put("title",
										getResources().getString(
												R.string.promotion));
								put("className",
										"com.applink.sell_proof.NewPromotionActivity");
								put("classShowing", getClassName());
							}
						});

						add(new HashMap<String, String>() {

							private static final long serialVersionUID = -7567381055807932459L;

							{
								put("title",
										getResources()
												.getString(R.string.event));
								// put("className",
								// "com.applink.sell_proof.LifeStyleActivity");
							}
						});
					}
				};

				mBuilder.setData(mapdata);

				mPopUpAnnoucement = new PopupWindow(this);
				mPopUpAnnoucement.setContentView(popuplayout);
				mPopUpAnnoucement.dismiss();
			}

			if (mPopUpAnnoucement.isShowing()) {
				mPopUpAnnoucement.dismiss();
			} else {

				int listheight = 0;

				if (mBuilder != null) {
					listheight = Utility
							.getListViewHeight(((PopupBuilder) mBuilder)
									.getListView());
				}

				View bottombar = findViewById(R.id.main_bottom_bar);
				if (bottombar == null)
					bottombar = findViewById(R.id.tab_bar_group);

				// get maximum possible height
				int heightAnnoucement = mPopUpAnnoucement
						.getMaxAvailableHeight(mLayout);
				int width = mLayout.getWidth() * 1 / 2;

				// location should be the bottom right
				mPopUpAnnoucement.showAtLocation(mLayout, Gravity.BOTTOM
						| Gravity.RIGHT, 0, heightAnnoucement);
				mPopUpAnnoucement.update(0, bottombar.getMeasuredHeight(),
						width, (listheight + 10));
			}

			break;
			// Intent intent = new Intent(this, LifeStyleActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
			// | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			// startActivity(intent);
			// break;
		}
		default:
			break;
		}
	}

	/**
	 * Called to process touch screen events.
	 */
	private long touchDownTime = 0;

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			touchDownTime = SystemClock.elapsedRealtime();
			break;

		case MotionEvent.ACTION_UP:
			// to avoid drag events
			if (SystemClock.elapsedRealtime() - touchDownTime <= 150) {

				if (mPopUpSell == null || !mPopUpSell.isShowing())
					return super.dispatchTouchEvent(ev);

				// To avoid later it come to the onClick even of Sell Tab
				if (isPointInsideView(ev.getRawX(), ev.getRawY(),
						findViewById(R.id.deal_tab))) {
					return super.dispatchTouchEvent(ev);
				}

				if (!isPointInsideView(ev.getRawX(), ev.getRawY(),
						mPopUpSell.getContentView())) {
					mPopUpSell.dismiss();
				}
			}
			break;
		}

		return super.dispatchTouchEvent(ev);
	}

	/**
	 * Determines if given points are inside view
	 * 
	 * @author Van Vu
	 * @param x
	 *            - x coordinate of point
	 * @param y
	 *            - y coordinate of point
	 * @param view
	 *            - view object to compare
	 * @return true if the points are within view bounds, false otherwise
	 */
	private boolean isPointInsideView(float x, float y, View view) {
		int location[] = new int[2];
		view.getLocationOnScreen(location);
		int viewX = location[0];
		int viewY = location[1];

		// point is inside view bounds
		if ((x > viewX && x < (viewX + view.getWidth()))
				&& (y > viewY && y < (viewY + view.getHeight()))) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * each of the findViews implementation from subclass should implement
	 */
	protected abstract void findViews();

	public void showloading() {
		MyProgressDialog.getInstance().show(this.getSupportFragmentManager(),
				null);
	}

	public void hideloading() {
		try {
			MyProgressDialog.getInstance().dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getClassName() {
		String ClassName = null;
		ActivityManager am = (ActivityManager) getApplication()
				.getSystemService(ACTIVITY_SERVICE);
		// get the info from the currently running task
		List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
		ClassName = taskInfo.get(0).topActivity.getClassName();
		return ClassName;
	}
}
